import type { FetchHomeDataProps } from './api'
import type { Dictionary } from '@/api/base/interface'
import type { HomeType } from './interface'

import { useLocalObservable, useObserver } from 'mobx-react'
import { fetchClassCategory, fetchHomeData } from './api'
import { observer } from 'mobx-react'
import { fetchDictList } from '@/api/base'
import { useEffect } from 'react'
import {
    CourseRanking,
    CourseStatistics,
    Header,
    GroupData,
    StudentStatistics,
    ResultProportion,
} from './components'
import { Toast } from 'antd-mobile'
import { stores } from '@/stores'
import { PlateSelector } from './components/Plate'
import { asserts } from '@/utils/share'

import dayjs from 'dayjs'
import styles from './index.module.less'

export default observer(() => {
    /** 默认选中的年份 */
    const defaultSelectedYear = String(dayjs().year())

    const store = useLocalObservable(() => ({
        /** 查询条件 */
        query: {
            year: defaultSelectedYear,
        } as FetchHomeDataProps,

        /** 页面数据 */
        homeData: {} as HomeType.Data,

        /** 年份选择器选项 */
        yarnOptions: {} as Dictionary.Res,

        /** 培训班类别择器选项 */
        classCategoryOptions: {} as Dictionary.Res,

        /** 获取字典 */
        async fetchDictsToStore() {
            const [decYearOptions] = await fetchDictList(['dec_year'])

            this.yarnOptions = { [0]: '全部', ...decYearOptions }
        },

        /** 获取培训班类别 */
        async initClassCategory() {
            const { data } = await fetchClassCategory()
            this.classCategoryOptions = data
        },

        /** 请求首页数据 */
        async fetchHomeDataToStore(params?: FetchHomeDataProps) {
            const tostShow = Toast.show({
                icon: 'loading',
                content: '加载中...',
                duration: 0,
            })

            const data = await fetchHomeData(params)

            tostShow.close()
            if (!data) return

            store.homeData = data
        },
    }))

    const { isCenterRole, isProvinceRole, isCompany, isCityRole } = stores.userStore
    const permission = {
        courseRanking: [isCenterRole, isProvinceRole].some(v => v === true),
        courseStatistics: [isCenterRole, isProvinceRole, isCompany, isCityRole].some(
            v => v === true,
        ),
    }

    useEffect(() => {
        store.fetchDictsToStore()
        store.initClassCategory()
        store.fetchHomeDataToStore(store.query)
    }, [defaultSelectedYear, store])

    const PickerYear = () => {
        return (
            <div
                style={{
                    marginBottom: 10,
                    display: 'flex',
                    width: 'calc(100% - 4vw)',
                }}
            >
                <div
                    style={{
                        marginLeft: 'auto',
                        backgroundColor: '#fff',
                        display: 'flex',
                        justifyContent: 'center',
                        alignItems: 'center',
                        padding: '2px 4px',
                        paddingLeft: '14px',
                        borderRadius: '4px',
                        userSelect: 'none',
                    }}
                >
                    <span>年份筛选:</span>
                    <PlateSelector
                        style={{
                            backgroundColor: '#fff',
                            paddingLeft: '4px',
                        }}
                        value={store.query.year ? [store.query.year] : undefined}
                        options={store.yarnOptions}
                        onConfirm={([v]) => {
                            if (!asserts.isString(v)) return

                            store.query.year = v
                            store.fetchHomeDataToStore(store.query)
                        }}
                    />
                </div>
            </div>
        )
    }

    return useObserver(() => {
        return (
            <div className={styles.page}>
                <Header />

                <div className={styles.content}>
                    {/* 年份 */}
                    <PickerYear />

                    <GroupData
                        itemClass={styles.groupData_item}
                        data={store.homeData.group_data ?? {}}
                    />

                    {permission.courseRanking && (
                        /** 开班排行榜 */
                        <CourseRanking
                            className={styles.plate}
                            data={store.homeData.china_map_data ?? []}
                            maxShow={5}
                        />
                    )}

                    {permission.courseStatistics && (
                        /** 开班统计 */
                        <CourseStatistics
                            className={styles.plate}
                            data={store.homeData.course_data ?? []}
                            maxShow={5}
                        />
                    )}

                    <StudentStatistics
                        className={styles.plate}
                        data={store.homeData.student_data ?? []}
                        classCategoryOptions={store.classCategoryOptions}
                        onSelectCursorType={v => {
                            store.query.category_id = v
                            store.fetchHomeDataToStore(store.query)
                        }}
                    />

                    <ResultProportion
                        className={styles.plate}
                        data={store.homeData.check_data ?? {}}
                    />
                </div>
            </div>
        )
    })
})
